<template>
    <div>
        <div class="tableButtonTool" v-if="toolbar">
            <common-button text="导出"
                           @click="exportList()">
            </common-button>
        </div>
        <div style="overflow-x: auto">
            <vxe-table
                    :data="currentData"
                    v-loading.iTable="loading"
                    :stripe="true"
                    ref="mutipleTable"
                    :height="height"
                    :highlight-current-row="true"
                    @checkbox-change="handleSelectionChange"
                    @checkbox-all="selectAllEvent"
                    @row-click="rowClick"
                    @cell-click="rowClick"
                    border
                    resizable
                    show-overflow
                    highlight-hover-row
                    show-header-overflow
                    :tree-props="{children: 'children'}"
                    header-row-class-name="tableHeader"
                    :row-class-name="rowClassName"
                    class="commonVxeTable"
                    tooltip-effect="light"
                    show-overflow-tooltip="true"
                    :context-menu="contextMenu"
                    @context-menu-click="menuClick"
                    :tooltip-config="{contentMethod: showTooltipMethod, enterable: true,theme:effect,delayHover:10000}"
                    :checkbox-config="{labelField: 'name', checkMethod: checkMethod}"
                    :autoResize="autoResize"
                    style="width: 100%">
                <!--:edit-config="{trigger: 'click', mode: 'cell'}"-->

                <vxe-table-column v-if="mutiSelect" type="selection" width="60px" align="center">
                </vxe-table-column>
                <vxe-table-column type="seq" :title="seqNumberTitle" :width="seqNumberTitleWidth" v-if="seqNumber"></vxe-table-column>
                <!--region 按钮操作组-->
                <vxe-table-column v-if="operates&&(operates.align=='left')" title="操作" align="center"
                                  :fixed="operates.fixed?'left':null"
                                  :width="operates.width">
                    <template slot-scope="scope">
                        <div class="operate-group">
                            <template v-for="(btn, key) in operates.list">
                                <div class="item"
                                     v-if="btn.show !== false && (btn.isShow == undefined || btn.isShow(scope.row))"
                                     :key='btn.id'>
                                    <template v-if="btn.cls">
                                        <el-tooltip class="item" :effect="effect" :content="btn.label" placement="top" :openDelay="1000">
                                            <image-button :cls="btn.cls" :disabled="btn.disabled"
                                                          @click.stop="btn.method(key,scope.row)">
                                            </image-button>
                                        </el-tooltip>
                                    </template>
                                    <template v-else>
                                        <inner-button :type="btn.type" size="mini" :icon="btn.icon"
                                                      :disabled="btn.disabled"
                                                      :text="btn.label"
                                                      :plain="btn.plain" @click.stop="btn.method(key,scope.row)">
                                        </inner-button>
                                    </template>
                                </div>
                            </template>
                        </div>
                    </template>
                </vxe-table-column>
                <!--endregion-->
                <template v-for="(column, index) in columns">
                    <vxe-table-column :field="column.propertyName||column.fieldName"
                                      :visible="!column.hidden"
                                      :key='column.propertyName||column.fieldName'
                                      :title="column.caption"
                                      :align="''+column.textAlignment"
                                      :sortable="systemSort&&column.allowSort"
                                      :show-overflow-tooltip="true"
                                      :min-width="column.minWidth"
                                      :edit-render="{name: 'input'}"
                                      :width="column.width">
                        <template slot-scope="scope">
                            <template v-if="!column.render">
                                <template v-if="column.formatter">
                                    <!--<span v-html="column.formatter(scope.row, column)"></span>-->
                                    <common-tooltip :tip="column.formatter(scope.row,column)">
                                        <span v-html="column.formatter(scope.row,column)"></span>
                                    </common-tooltip>
                                </template>
                                <template v-else-if="(column.propertyName||column.fieldName) === 'location' && column.caption === '位置'">
                                    <i class="fa fa-eye cur-p" style="color:rgb(110, 120, 130);font-size:15px;"
                                       :title="scope.row[(column.propertyName||column.fieldName)]"></i>
                                </template>
                                <template v-else-if="column.dictData">
                                   <!-- <span>{{scope.row[column.fieldName + '_Text']}}</span>-->
                                    <common-tooltip :tip="scope.row[column.propertyName + '_Text']||scope.row[column.fieldName + '_Text']">
                                        <span v-html="scope.row[column.propertyName + '_Text']||scope.row[column.fieldName + '_Text']"></span>
                                    </common-tooltip>
                                </template>
                                <template v-else>
                                    <common-tooltip :tip="scope.row[(column.propertyName||column.fieldName)]">
                                        <span v-html="scope.row[(column.propertyName||column.fieldName)]"></span>
                                    </common-tooltip>
                                  <!--  {{column.propertyName||column.fieldName}}-->
                                    <!--{{scope.row[column.propertyName]}}
                                    {{scope.row[column.fieldName]}}-->
                                </template>
                            </template>
                            <template v-else>
                                <expand-dom :column="column" :row="scope.row" :render="column.render"
                                            :index="index"></expand-dom>
                            </template>
                        </template>
                    </vxe-table-column>
                </template>
                <!--region 按钮操作组-->
                <vxe-table-column v-if="operates&&(operates.align == undefined || operates.align=='right')" title="操作"
                                  align="center"
                                  :fixed="operates.fixed?'right':null"
                                  :width="operates.width">
                    <template slot-scope="scope">
                        <div class="operate-group">
                            <template v-for="(btn, key) in operates.list">
                                <div class="item"
                                     v-if="btn.show !== false && (btn.isShow == undefined || btn.isShow(scope.row))"
                                     :key='btn.id'>
                                    <template v-if="btn.cls">
                                        <el-tooltip class="item" :effect="effect" :content="btn.label" placement="top" :openDelay="1000">
                                            <image-button :cls="btn.cls" :disabled="btn.disabled"
                                                          @click.stop="btn.method(key,scope.row)">
                                            </image-button>
                                        </el-tooltip>
                                    </template>
                                    <template v-else>
                                        <inner-button :type="btn.type" size="mini" :icon="btn.icon"
                                                      :disabled="btn.disabled"
                                                      :text="btn.label"
                                                      :plain="btn.plain" @click.stop="btn.method(key,scope.row)">
                                        </inner-button>
                                    </template>
                                </div>
                            </template>
                        </div>
                    </template>
                </vxe-table-column>
                <!--endregion-->
            </vxe-table>
            <el-row>
                <el-col :span="24" class="pager"  v-if="isPage">
                    <el-pagination layout="total, sizes, prev, pager, next, jumper"
                                   @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                   :page-sizes="[30,50,100]" :page-size="pageSize" :total="total"
                                   style="float:right;">
                    </el-pagination>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
    import Service from '../../../services/common.service'
    import {exportExcel} from '../../../../utils/excel/util'
    import moment from 'moment'

    export default {
        data() {
            return {
                currentData : this.data ? this.data : [],
                total: 0,
                pageSize: window.localStorage.getItem("systemSetting")?JSON.parse(window.localStorage.getItem("systemSetting"))['common.default_page_size']/1:30,
                page: 1,
                parameters: {},
                loading: false,
                systemSort: true
            }
        },
        components: {
            expandDom: {
                functional: true,
                props: {
                    row: Object,
                    render: Function,
                    index: Number,
                    column: {
                        type: Object,
                        default: null
                    }
                },
                render: (h, ctx) => {
                    const params = {
                        row: ctx.props.row,
                        index: ctx.props.index
                    }
                    if (ctx.props.column) params.column = ctx.props.column
                    return ctx.props.render(h, params)
                }
            }
        },
        watch: {
            params(val) {
                this.setParameters(val)
            },
            data(val) {
                this.currentData = this.data;
            }
        },
        mounted() {


        },
        created: function () {
            this.page = 1;
            if (window.localStorage.getItem("systemSetting")) {
                let settings = JSON.parse(window.localStorage.getItem("systemSetting"));
                let showSort = settings['ui.table.column.header.showSort'] == undefined ? true : settings['ui.table.column.header.showSort'];
                this.systemSort = (showSort == false || ('' + showSort).toUpperCase() == 'FALSE') ? false : true;
            }
        },
        methods: {
            reset() {
                const me = this;
                me.page = 1;
                setTimeout(function () {
                    me.getData()
                }, 50);
            },
            clear() {
                const me = this;
                me.page = 1;
                me.currentData = [];
                me.total = 0;
            },
            refresh() {
                this.getData();
            },
            setParameters(val) {
                this.parameters = val;
                if (this.autoPost) {
                    this.reset();
                }
            },
            // 单选事件
            handleSelectionChange({checked, records}) {
                this.$emit('selectChangeEvent', checked, records);
                let selectRecords = this.$refs.mutipleTable.getCheckboxRecords()
                this.$emit('selection-change', selectRecords)
            },
            //全选事件
            selectAllEvent({checked, records}) {
                this.$emit('selectAllEvent', checked, records);
                let selectRecords = this.$refs.mutipleTable.getCheckboxRecords()
                this.$emit('selection-change', selectRecords)
            },
            // 显示 表格操作弹窗
            showActionTableDialog() {
                this.$emit('handelAction')
            },

            rowClick(row, column, event) {
                this.$emit('rowClick', row.row)
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.getData();
            },

            handleCurrentChange(val) {
                this.page = val;
                this.getData();
            },

            getData() {
                const me = this;
                if(!me.isPage){
                    return me.currentData;
                }
                me.parameters = me.params;
                me.parameters['page'] = me.page;
                me.parameters['pageSize'] = me.pageSize;
                me.parameters['pageCondition'] = {
                    page: me.page, pageSize: me.pageSize
                };
                me.loading = true;

                Service.post(me.url, me.parameters).then((res) => {
                    me.loading = false;
                    if (res.data.succeeded == true) {
                        me.currentData = res.data.data;
                        me.total = res.data.totalRecords;
                    } else {
                        me.currentData = [];
                        me.total = 0;
                        me['$message']({
                            message: res.data.errorMessage,
                            type: 'error'
                        });
                        //
                    }
                });
            },

            exportList(fileName) {
                const me = this;
                if (!fileName) {
                    fileName = me.exportFileName;
                }
                let data = JSON.parse(JSON.stringify(me.currentData));
                for(let col of me.columns) {
                    if(col.formatter) {
                        for (let item of data) {
                            item[col.propertyName] = col.formatter(item);
                        }
                    }
                }

                exportExcel(me.columns, data, fileName + (me.isPage? ('-' + me.page):''));
            },

            menuClick(metadata, event){
//                console.log(metadata.menu)
                if(metadata.menu.code == 'test'){
//                    console.log(metadata.menu.name)
                }
            },

            // 重写默认的提示内容
            showTooltipMethod({type, column, row, items, _columnIndex}) {
                // 重写默认的提示内容
                if (column.title === '具体流程' && row && row.stepInstances && row.stepInstances.length > 0 && column.property === 'stepInstances') {
                    let html = '', html2;
                    for (let item of row.stepInstances) {
                        if (item.status !== 4) {
                            html += `${item.name + '(' + item.actualApproverName + ')' + ' —> '}`
                        }
                    }
                    html2 = html.split(' —> ');
                    html2.splice(html2.length - 1, 1);
                    return html2.join(' —> ');
                } else if (column.type == 'selection' &&row && row.canBorrow === false && row.reason) {
                    return row.reason;
                } else if (column.type == 'selection' &&row && row.canChangeBorrower === false && row.reason) {
                    return row.reason;
                } else if(column.type == 'selection' && this.isLendout && row && row.canLendOut === false && row.lendOutReason){
                    return row.lendOutReason;
                }
            },

            checkMethod({row}) {
                if (this.isLendout && row.canLendOut === false) {
                    return false;
                }
                if (row.canChangeBorrower == false) {
                    return false;
                }
                return true;
            }
        },
        props: {
            data: {
                type: Array,
                default: function () {
                    return [];
                }
            },

            contextMenu: {
                type: [Object, Function],
                default: function () {
                    return {
                        header: {
                            disabled: false,
                            options: [[
                                {
                                    code: 'RESET_RESIZABLE',
                                    name: '重置列宽'
                                },
                                {
                                    code: 'SORT_ASC',
                                    name: '升序'
                                },
                                {
                                    code: 'SORT_DESC',
                                    name: '降序'
                                },
                                {
                                    code : 'FIXED_LEFT_COLUMN',
                                    name: '固定左侧'
                                },
                                {
                                    code : 'FIXED_RIGHT_COLUMN',
                                    name: '固定右侧'
                                },
                                {
                                    code : 'CLEAR_FIXED_COLUMN',
                                    name: '清除固定列'
                                },
                                {
                                    code : 'HIDDEN_COLUMN',
                                    name: '隐藏当前列'
                                },
                                {
                                    code : 'RESET_COLUMN',
                                    name: '重置列的可视状态'
                                },
                                {
                                    code : 'test',
                                    name: '自定义'
                                }
                            ]]
                        }
                    };
                }
            },

            columns: {
                type: Array,
                default: () => []
            },

            operates: {},

            mutiSelect: false,

            height: Number,

            url: String,

            params: {
                type: Object,
                default: () => {
                }
            },

            autoPost: {
                type: Boolean,
                default: false
            },
            toolbar: {
                type: Boolean,
                default: false
            },
            rowKey: {
                type: String,
                default: 'id'
            },
            isPage: {
                type: Boolean,
                default: true
            },
            seqNumberTitle: {
                type: String,
                default: '序号'
            },
            seqNumberTitleWidth: {
                type: String,
                default: '50'
            },
            seqNumber:{
                type: Boolean,
                default: false
            }, // 是否显示序号
            exportFileName: {
                type: String,
                default: 'ExportData'
            },
            autoResize: {
                type:Boolean,
                default: true
            },
            effect:{
                type: String,
                default: 'dark'//light
            },
            rowClassName: {
                type: [String, Function],
            }
        },
    }
</script>
<style lang="scss" scoped>
    /*.commonTable {
        margin-top: 3px;
        td, th{
            padding: 4px 0;
            text-align: center;
        }
        td{
            font-size: 0.875rem;
            color: #333;
        }
        .tableHeader th{
            background-color: #205193;
            color: #fff;
            padding: 5px 0;
            text-align: center;
            border-right: 1px solid #EBEEF5 !important;
        }
    }*/
</style>
